package com.travelbid.admin.struts.action;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.springframework.web.struts.ActionSupport;
import com.travelbid.admin.pojo.TUser;
import com.travelbid.admin.service.AdminUserService;

public class AdminEnterAction extends ActionSupport {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("text/xml;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		try {
			Cookie nameCookie = null;
			Cookie passCookie = null;
			Cookie[] cookieset = request.getCookies();
			if(cookieset != null)
			{
				for (int i = 0; i < cookieset.length; i++) {
					if (cookieset[i].getName().equals("Name"))
						nameCookie = cookieset[i];
					else if (cookieset[i].getName().equals("Pass"))
						passCookie = cookieset[i];
				}
			}
			AdminUserService service = (AdminUserService)getWebApplicationContext().getBean("AdminUserService");
			TUser user =null;
			if((nameCookie!=null)&&(passCookie!=null))
			   user = service.isAdminExist(nameCookie.getValue(), passCookie
					.getValue(), 2); // 外部用户不能登陆

			HttpSession session = request.getSession();
			if (user != null) {
				session.setAttribute("USER_ID", user.getId());
				session.setAttribute("USER_NAME", user.getUsername());
				session.setAttribute("user", user);
				Date d = new Date();
				session.setAttribute("loginTime", d);
				return mapping.findForward("adminMainPage");
			} else {
				return mapping.findForward("adminEnter");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mapping.findForward("adminEnter");
	}
}
